import Icon from '@ant-design/icons';
import { Button, Input } from 'antd';
import type { LngLat } from 'mapbox-gl';
import { useRef } from 'react';
import { message } from '@/components/AntdWrapper';
import type Mapless from '../../Mapless';
import copySvg from './copy.svg?react';
import DraggableMarker from './Index';

type DraggableMarkerGroupProps = {
  mapless?: Mapless | undefined;
  markers?: LngLat[];
};

const DraggableMarkerGroup = ({
  mapless,
  markers,
}: DraggableMarkerGroupProps) => {
  const inputValuesRef = useRef<Record<string, string>>({});

  const getInputValue = (marker: LngLat) => {
    return inputValuesRef.current[JSON.stringify(marker)];
  };

  return (
    <>
      {markers?.map((m) => {
        return (
          <DraggableMarker
            key={JSON.stringify(m)}
            mapless={mapless}
            lngLat={m}
            anchor="bottom"
          >
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Input
                style={{ width: 100, marginRight: 4 }}
                size="small"
                onChange={(e) => {
                  inputValuesRef.current[JSON.stringify(m)] = e.target.value;
                }}
              />
              <Button
                icon={<Icon component={copySvg} />}
                size="small"
                onClick={() => {
                  let coordText = `经度: ${m.lng.toFixed(6)}, 纬度: ${m.lat.toFixed(6)}`;
                  const remark = getInputValue(m);
                  if (remark) {
                    coordText += `, 备注: ${remark}`;
                  }
                  navigator.clipboard
                    .writeText(coordText)
                    .then(() => {
                      message.info(`坐标已复制: ${coordText}`);
                    })
                    .catch(() => {
                      message.info(`坐标获取成功: ${coordText}`);
                    });
                }}
              />
            </div>
          </DraggableMarker>
        );
      })}
    </>
  );
};

export default DraggableMarkerGroup;
